import { login, logout, getInfo } from "@/api/user";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { resetRouter,constantRoutes,asyncRoutes, anyRoutes } from "@/router";
import router from '@/router'
const getDefaultState = () => {
  return {
    token: getToken(),
    //用户名
    name: "",
    //用户头像
    avatar: "",
    //路由
    routes:[],
    //角色
    roles:[],
    //按钮权限
    buttons:[],
    //经过对比后应该展示的异步路由
    resultAsyncroutes:[],
    //最终要展示的菜单
    resultAllroutes:[],
    a:constantRoutes
  };
};

const state = getDefaultState();

const mutations = {
  //清除state
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState());
  },
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  SET_ROUTES:(state,data)=>{
    state.routes=data.routes;
    state.roles=data.roles;
    state.buttons=data.buttons;
  },
  SET_RESULTASYNCROUTES:(state,result)=>{
    state.resultAsyncroutes=result
    router.addRoutes(state.resultAsyncroutes)
  },
};

const actions = {
  // user login
  async login({ commit }, userInfo) {
    const { username, password } = userInfo;
    let result = await login({ username: username.trim(), password: password });
    console.log(result);
    if (result.code === 20000 || result.code === 200) {
      commit("SET_TOKEN", result.data.token);
      console.log(result);
      setToken(result.data.token);
      return "ok";
    } else {
      return Promise.reject(new Error("Error"));
    }
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token)
        .then((response) => {
          const { data } = response;
          console.log(asyncRoutes);
          //存储路由以及权限
          commit('SET_ROUTES',data)
          if (!data) {
            return reject("Verification failed, please Login again.");
          }
          const { name, avatar } = data;

          commit("SET_NAME", name);
          commit("SET_AVATAR", avatar);
          commit("SET_RESULTASYNCROUTES",computedResultRoutes(asyncRoutes,data.routes))
          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          removeToken(); // must remove  token  first
          resetRouter();
          commit("RESET_STATE");
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken(); // must remove  token  first
      commit("RESET_STATE");
      resolve();
    });
  },
};
function computedResultRoutes(asyncRoutes,routes){
  return asyncRoutes.filter(item=>{
    if (routes.indexOf(item.name)!==-1) {
      if (asyncRoutes.children&&asyncRoutes.children.length>0) {
      computedResultRoutes(asyncRoutes.children,routes)
    }
      return true;
    }
    
    
  })
}
export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
